<template>
  <div class="container">
    <div class="address">
      <!-- 地址渲染 -->
      <van-address-list
        :list="addressData"
        default-tag-text="默认"
        :switchable="false"
        class="address_list"
      />
      <van-divider
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 0' }"
        dashed
      />
    </div>
    <div class="goods_list">
      <!-- 购物车商品渲染 -->

      <van-card
        v-for="item in goodsList"
        :key="item"
        :num="item.count"
        :price="(item.goods_info.price / 100).toFixed(2)"
        :desc="item.goods_info.detail_info"
        :title="item.goods_info.name"
        :thumb="item.goods_info.pic_url"
      />
    
    </div>
  </div>
     <van-submit-bar
      :price="countPrice"
      button-text="生成订单"
      @submit="show=true"
    >
      <template #tip>
        <van-field
          v-model="remark"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          maxlength="50"
          placeholder="备注"
          show-word-limit
        />
      </template>
    </van-submit-bar>
    <van-action-sheet
  v-model:show="show"
  :actions="actions"
  cancel-text="取消"
  close-on-click-action
  @cancel="onCancel"
   @select="onSelect"
/>
</template>

<script setup>
import { computed, onMounted, ref, watchEffect } from "vue";
import { useRoute,useRouter } from "vue-router";
import { getAddressList } from "@/api/address";
import { storeToRefs } from "pinia";
import userCartInfo from "@/stores/userCartInfo";
import {orderAdd} from '@/api/order'
import { showSuccessToast } from "vant";
import {cartDelete} from '@/api/cart'
import {getGoodsDetail} from '@/api/goods'
let route = useRoute();
let router = useRouter()
let cartStore = userCartInfo();
let remark=ref('')
// 选中的地址
let addressData = ref([]);
let { list } = storeToRefs(cartStore);
// 选中的购物车数据
let goodsList = ref([]);
onMounted(async () => {
  let arr = (await getAddressList({ limit: 100, page: 1 })).data.list;

  let adressArr = arr.filter((item) => item.id == route.query.addressId);
  addressData.value = adressArr.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town + item.detail,
      isDefault: item.is_default === 1,
    };
  });
//表示从商品也买你  直接下单
if(route.query.goodsId){
    let goodsInfo =(await getGoodsDetail({id:route.query.goodsId})).data;
    let goodsItem={
        count:1,
        goods_info:goodsInfo,
        goods_id:route.query.goodsId,
    }
    goodsList.value=[goodsItem]
}

  
});
watchEffect(() => {
    if(route.query.checkedGoods){
             let goodsIds = route.query.checkedGoods.split(",");
  goodsList.value = list.value.filter((item) =>
    goodsIds.includes(item.id.toString())
  );
    }
 
});
  let countPrice =computed(()=>{
    let countPrice=0
    goodsList.value.forEach(item=>{
        countPrice+=item.count*item.goods_info.price
    })
    return  countPrice
})
//控制动作面板显示隐藏
let show=ref(false)
//动作面板选项
const actions =[
    {name:'微信',pay_type:1},
    {name:'支付宝',pay_type:2},
    {name:'云闪付',pay_type:3}
]
let onSubmit=()=>{

}
//点击了取消的事件
let  onCancel= async ()=>{
    const data={
        remark:remark.value,  //备注
        status:'1', //状态   1为待支付订单
        price:countPrice.value,  //总价格
        order_goods_infos:goodsList.value.map((item)=>{
            return {
                goods_id:item.goods_id,
                count:item.count
            }
        }),   // 商品列表
        addressId:addressData.value[0].id  //地址
    }
    // 调用接口 传递数据  生成订单
    await orderAdd(data)
    showSuccessToast('生成订单成功')
    // 从购物车内 删除 刚才已下单的商品
    if(route.query.checkedGoods){
         cartDelete({ ids: goodsList.value.map((item)=>item.id) });
          cartStore.getCartInfo()
    }
   
    // 调用action  更新 购物车仓库数据
    cartStore.getCartInfo()
    // 返回首页
    router.replace('/home')
}
let onSelect=async (action,index)=>{
    // console.log(action);
    // console.log(index);
    // 创建接口 需要的参数
    const data={
        pay_type:action.pay_type,  // 支付方式
        remark:remark.value,  //备注
        status:'2', //状态
        price:countPrice.value,  //总价格
        order_goods_infos:goodsList.value.map((item)=>{
            return {
                goods_id:item.goods_id,
                count:item.count
            }
        }),   // 商品列表
        addressId:addressData.value[0].id  //地址
    }
    console.log(data);
    // 调用接口 传递数据  生成订单
    await orderAdd(data)
    showSuccessToast('生成订单成功')
    // 从购物车内 删除 刚才已下单的商品
    if(route.query.checkedGoods){
 cartDelete({ ids: goodsList.value.map((item)=>item.id) });
 cartStore.getCartInfo()
    }
   
    // 调用action  更新 购物车仓库数据
    
    // 返回首页
    router.replace('/home')
}

</script>
<style lang="scss" scoped>
.container{
        --van-submit-bar-z-index:100;
        --van-address-list-add-button-z-index:1;
        --van-submit-bar-tip-background:#f0f0f0;
}
 
</style>